import { useEffect } from 'react';

import commonService from '@/api/services/commonService';
import userStore, { useUserActions } from '@/store/userStore';

export default function CallbackPage() {
  const action = useUserActions();

  const getQueryString = (search: string, name: string) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const r = search.match(reg);
    if (r != null) {
      return decodeURI(r[2]);
    }
    return null;
  };

  useEffect(() => {
    const { hash } = window.location;
    const code = getQueryString(hash.substring(11), 'code');
    if (code) {
      commonService.getCustomApi('/callback', { code }).then((res) => {
        const { member, token } = res;
        userStore.getState().actions.setUserToken({ accessToken: token });
        userStore.getState().actions.setUserInfo(member);
        action.setShowLogin(false);
        window.location.href = '/#/index';
      });
    }
  }, []);

  return <div>授权登录中</div>;
}
